package android.test.devicetest;

import java.io.File;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import com.android.internal.telephony.ITelephony;
import com.android.internal.telephony.IccCard;
import com.android.internal.telephony.TelephonyIntents;

public class BootReceiver extends BroadcastReceiver {
    private final String TAG = "BootReceiver";
    private static final int MSG_SIM_PIN_REQUIRED = 1;
    private static final int MSG_SIM_PUK_REQUIRED = 2;
    private static final String DEF_PIN_CODE = "0000";

    private boolean isWikangoApkExists()
    {
        File wikangoxl = new File("/system/app/wikango_xl.apk");
        return wikangoxl.exists();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        final String action = intent.getAction();
        if (TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(action)) {
            // wikango apk exists
//          if (isWikangoApkExists()) return;

            String stateExtra = intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE);
            if (IccCard.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) {
                final String lockedReason = intent.getStringExtra(IccCard.INTENT_KEY_LOCKED_REASON);
                if (IccCard.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)) {
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SIM_PIN_REQUIRED, 0));
                    Log.d(TAG, "PIN_REQUIRED");
                } else if (IccCard.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SIM_PUK_REQUIRED, 0));
                    Log.d(TAG, "PUK_REQUIRED");
                } else {
                    Log.d(TAG, "UNKNOWN");
                }
            }
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_SIM_PIN_REQUIRED:
                unlockSimPin();
                break;
            case MSG_SIM_PUK_REQUIRED:
                unlockSimPuk();
                break;
            }
        }
    };

    private void unlockSimPin() {
        new Thread() {
            @Override
            public void run() {
                try {
                    String  pin    = SystemProperties.get("persist.sys.sim.pin", DEF_PIN_CODE);
                    boolean result = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")).supplyPin(pin);
                } catch (RemoteException e) {}
            }
        }.start();
    }

    private void unlockSimPuk() {
        // todo..
    }
}
